package com.kstech.exccheck.receiver;

import android.content.Intent;
import android.os.Bundle;

import com.kstech.exccheck.util.AppContext;

import java.text.DecimalFormat;
import java.util.HashMap;

import J1939.J1939_DTCfg_ts;
import J1939.J1939_DataVar_ts;
import com.kstech.exccheck.config.vo.ResourceVO.MsgVO;

/**
 * Created by lenovo on 2016/10/28.
 */
public class RealTimeChangedListener implements ReceivedDataKey{

    private J1939_DataVar_ts dataVar;

    /**
     * Instantiates a new Real time changed listener.
     *
     * @param dataVar the data var
     */
    public RealTimeChangedListener(J1939_DataVar_ts dataVar) {
        super();
        this.dataVar = dataVar;
    }

    /**
     * On changed. 把接收到的数据进行 格式转换 数据包装 发送广播到RealTimeParamReceiver{@linkplain RealTimeParamReceiver}
     */
    public void onChanged(){
        Intent sendIntent = new Intent();
        HashMap map = new HashMap();
        // 保留小数点位数
        byte bDataDec = dataVar.bDataDec;
        StringBuffer sb = new StringBuffer();
        if (bDataDec!=0) {
            sb.append(".");
            for (int i=0;i < bDataDec;i++) {
                sb.append("0");
            }
        }
        DecimalFormat decimalFormat=new DecimalFormat(sb.toString());//构造方法的字符格式这里如果小数不足2位,会以0补足.

        if(dataVar.isFloatType()){
            Float value = dataVar.getFloatValue();
            String formatValue = decimalFormat.format(value);
            System.out.println(formatValue);
            if(".".equals(formatValue.substring(0,1))) {
                formatValue = "0" + formatValue;
            }
            if("0".equals(formatValue)){
                formatValue = "0";
            }
            map.put(dataVar.sName, formatValue);
        }else{
            Long value = dataVar.getValue();
            String formatValue = decimalFormat.format(value);
            if(value == 0) {
                formatValue = "0" + formatValue;
            }
            map.put(dataVar.sName, formatValue);
        }

        Bundle bundle = new Bundle();
        bundle.putSerializable(REAL_PARAM_DATA, map);

        J1939_DTCfg_ts dtc = AppContext.getModelFile().getJ1939PgSetVO().getLastErrorDtc(dataVar.sName);
        if(dtc != null){
            //说明传感器有故障
            MsgVO msgVO = AppContext.getResConfig().getResourceVO().getMsgVO(dtc.wDescId);
            bundle.putSerializable(ERROR_MSG, msgVO);
        }
        sendIntent.putExtras(bundle);
        sendIntent.setAction(RealTimeChangedListener.class.getName());

        // 数据区数据变化，发送广播
        AppContext.context.sendBroadcast(sendIntent);
    }
}
